<template>
  <div>
    <div style="padding: 5px 0">
      <el-input v-model="searchText" @keyup.enter="load" style="width: 200px">
        <template #prefix>
          <i class="el-input__icon iconfont icon-r-find"></i>
        </template>
      </el-input>
      <br />
      <el-button @click="load" type="primary" style="margin: 5px"
        >搜索</el-button
      >
      <el-button @click="reset" type="warning" style="margin: 5px"
        >重置</el-button
      >
      <el-button @click="add" type="success" style="margin: 5px"
        >新增</el-button
      >
    </div>

    <el-table :data="tableData" border stripe style="width: 100%">
      <el-table-column prop="id" label="商品id" width="80px"></el-table-column>
      <el-table-column prop="name" label="商品名称"></el-table-column>
      <el-table-column label="商品图片" width="120px">
        <template #default="scope">
          <img
            :src="baseApi + scope.row.imgs"
            style="width: 90px; height: 80px"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="description"
        label="商品描述"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column prop="discount" label="折扣"></el-table-column>
      <el-table-column prop="sales" label="销量"></el-table-column>
      <el-table-column prop="saleMoney" label="销售额（元)"></el-table-column>
      <el-table-column prop="createTime" label="创建时间">
        <template #default="scope">
          {{ scope.row.createTime.replace(" ", "&nbsp;&nbsp;") }}
        </template>
      </el-table-column>
      <el-table-column label="推荐" width="150">
        <template #default="scope">
          <el-switch
            v-model="scope.row.recommend"
            @change="handleRecommend(scope.row)"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="250">
        <template #default="scope">
          <el-button
            type="primary"
            style="font-size: 18px"
            @click="edit(scope.row)"
            >修改</el-button
          >
          <el-popconfirm @confirm="del(scope.row.id)" title="确定删除？">
            <template #reference>
              <el-button
                type="danger"
                style="font-size: 18px; margin-left: 10px"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 10px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-size="pageSize"
        :page-sizes="[3, 5, 8, 10]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialogFormVisible"
      title="信息"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="entity">
        <el-form-item label="商品名称" label-width="150px">
          <el-input
            v-model="entity.name"
            autocomplete="off"
            style="width: 80%"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品描述" label-width="150px">
          <el-input
            v-model="entity.description"
            autocomplete="off"
            style="width: 80%"
          ></el-input>
        </el-form-item>
        <el-form-item label="折扣" label-width="150px">
          <el-input
            v-model="entity.discount"
            autocomplete="off"
            style="width: 80%"
          ></el-input>
        </el-form-item>
        <el-form-item label="分类id" label-width="150px">
          <el-input
            v-model="entity.categoryId"
            autocomplete="off"
            style="width: 80%"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品图片" label-width="150px">
          <el-upload
            class="upload-demo"
            ref="upload"
            :action="baseApi + '/file/upload'"
            :file-list="fileList"
            :on-change="handleChange"
            :limit="2"
            :on-success="handleImgSuccess"
            :auto-upload="false"
          >
            <template #trigger>
              <el-button size="small" type="primary">选取文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogFormVisible = false" style="font-size: 20px"
          >取消</el-button
        >
        <el-button type="primary" @click="save" style="font-size: 20px"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";

const store = useStore();
const router = useRouter();

// Reactive data
const baseApi = ref<string>(store.state.baseApi);
const searchText = ref<string>("");
const tableData = ref<any[]>([]);
const pageNum = ref<number>(1);
const pageSize = ref<number>(5);
const entity = ref<any>({});
const total = ref<number>(0);
const dialogFormVisible = ref<boolean>(false);
const fileList = ref<any[]>([]);
const upload = ref<any>(null);

// Methods
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  load();
};

const handleCurrentChange = (page: number) => {
  pageNum.value = page;
  load();
};

const handleRecommend = (good: any) => {
  store.state.request
    .get("/api/good/recommend", {
      params: {
        id: good.id,
        isRecommend: good.recommend,
      },
    })
    .then((res: any) => {
      if (res.code === "200") {
        store.state.message.success("修改成功");
      } else {
        store.state.message.error(res.msg);
      }
    });
};

const load = () => {
  store.state.request
    .get("/api/good/fullPage", {
      params: {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        searchText: searchText.value,
      },
    })
    .then((res: any) => {
      tableData.value = res.data.records;
      total.value = res.data.total;
    });
};

const reset = () => {
  searchText.value = "";
  load();
};

const add = () => {
  router.push("goodInfo");
};

const edit = (obj: any) => {
  entity.value = JSON.parse(JSON.stringify(obj));
  router.push({
    name: "goodInfo",
    query: { good: JSON.stringify(entity.value) },
  });
};

const handleImgSuccess = (res: any) => {
  entity.value.imgs = res.data;
  store.state.request.post("/api/good/", entity.value).then((res2: any) => {
    if (res2.code === "200") {
      store.state.message.success("操作成功");
    } else {
      store.state.message.error(res2.msg);
    }
    load();
    dialogFormVisible.value = false;
  });
};

const save = () => {
  if (fileList.value.length !== 0) {
    upload.value.submit();
  } else {
    store.state.request.post("/api/good/", entity.value).then((res2: any) => {
      if (res2.code === "200") {
        store.state.message.success("操作成功");
      } else {
        store.state.message.error(res2.msg);
      }
      load();
      dialogFormVisible.value = false;
    });
  }
};

const del = (id: any) => {
  store.state.request.delete("/api/good/" + id).then(() => {
    store.state.message.success("操作成功");
    load();
  });
};

const handleChange = (file: any, files: any[]) => {
  fileList.value = files.slice(-3);
};

// Lifecycle
onMounted(() => {
  load();
});
</script>

<style scoped></style>
